package com.green.cosme.util;

import java.io.IOException;
import java.io.Writer;
import java.text.DateFormat;
import java.util.TimeZone;
import java.util.logging.Logger;

import org.apache.velocity.Template;
import org.apache.velocity.app.Velocity;
import org.apache.velocity.context.Context;
import org.apache.velocity.runtime.log.JdkLogChute;

/**
 * Renderer class
 * 
 * @author masato tsuchida
 * 
 */
public class Renderer {

	// Get logger
	static Logger logger = Logger.getAnonymousLogger();

	private static boolean initialized = false;

	// initialize velocity
	private static void initializeVelocity() throws Exception {
		Velocity.setProperty(Velocity.RUNTIME_LOG_LOGSYSTEM, new JdkLogChute());
		Velocity.init();
		initialized = true;
	}

	private static DateFormat dateTimeFormat = DateFormat.getDateTimeInstance();
	static {
		dateTimeFormat.setTimeZone(TimeZone.getTimeZone("JST"));
	}

	// execute render using velocity
	public static void render(String filename, Context context, Writer writer) throws IOException {
		try {
			// exclude when execute initialization
			synchronized (logger) {
				if (!initialized)
					initializeVelocity();
			}
			// reflect data to outputStream(response)
			Template template = Velocity.getTemplate(filename);
			template.merge(context, writer);

		} catch (Exception e) {
			throw new IOException(e);
		}
	}
}
